<template>
  <div>
    <el-row>
      <el-col :span="16">
        <div class="chat-container" :style="{ '--local-mount-height': cssVar ? `var(${cssVar})` : '100%' }">
    <!-- 控制区域 - 模型选择和操作按钮 -->
    <div class="control-area">
      <div class="model-selector">
        <el-select
          v-model="selectedModel"
          :disabled="isLoadingModels"
          placeholder="选择模型"
          size="large"
          filterable
          allow-create
        >
          <el-option
            v-for="model in availableModels"
            :key="model.slug"
            :label="model.name"
            :value="model.slug"
          >
            <div class="model-option">
              <span class="model-name">{{ model.name }}</span>
              <span v-if="model.reasoning" class="model-badge">推理</span>
            </div>
          </el-option>
        </el-select>
        <el-button
          v-if="isLoadingModels"
          :loading="true"
          type="info"
          size="large"
          class="loading-button"
        >
          加载模型中...
        </el-button>
      </div>

      <div class="action-buttons">
        <el-tooltip content="清空对话历史" placement="bottom">
          <el-button
            @click="clearChat"
            :disabled="messages.length === 0"
            type="danger"
            size="large"
            circle
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 消息展示区域 -->
    <div class="messages-container">
      <div class="messages" ref="messagesContainer">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.role]"
        >
          <div class="avatar">
            <el-avatar
              v-if="msg.role === 'user'"
              :size="40"
              :icon="UserFilled"
              class="user-avatar"
            />
            <el-avatar
              v-else
              :size="40"
              :icon="Cpu"
              class="ai-avatar"
            />
          </div>

          <div class="message-content">
            <div class="message-header">
              <strong>{{ msg.role === 'user' ? '你' : 'AI助手' }}</strong>
              <span class="timestamp">{{ formatTimestamp(msg.timestamp) }}</span>
            </div>
            <div class="message-body" v-html="formatMessage(msg.content)"></div>
          </div>
        </div>

        <div v-if="isLoading" class="message ai thinking">
          <div class="avatar">
            <el-avatar :size="40" :icon="Cpu" class="ai-avatar" />
          </div>
          <div class="message-content">
            <div class="message-header">
              <strong>AI助手</strong>
            </div>
            <div class="message-body">
              <div class="thinking-indicator">
                <span>思考中</span>
                <span class="dot">.</span>
                <span class="dot">.</span>
                <span class="dot">.</span>
              </div>
            </div>
          </div>
        </div>

        <div v-if="messages.length === 0" class="empty-state">
          <div class="empty-content">
            <el-icon :size="60" class="empty-icon"><ChatRound /></el-icon>
            <h3>开始新的对话</h3>
            <p>选择一个模型，然后输入消息开始聊天</p>
            <div class="model-tips">
              <el-tag v-for="model in modelTips" :key="model.slug" type="info" size="large">
                {{ model.name }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="3"
        placeholder="输入消息..."
        resize="none"
        @keydown.enter.exact.prevent="sendMessage"
        class="input-textarea"
      >
      </el-input>

      <div class="input-actions">
        <el-tooltip content="清空输入" placement="top">
          <el-button
            @click="userInput = ''"
            :disabled="!userInput.trim()"
            circle
            class="action-button"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </el-tooltip>

        <el-button
          @click="sendMessage"
          :disabled="isLoading || !userInput.trim()"
          type="primary"
          size="large"
          class="send-button"
        >
          <template #icon>
            <el-icon v-if="!isLoading"><Promotion /></el-icon>
            <el-icon v-else class="is-loading"><Loading /></el-icon>
          </template>
          {{ isLoading ? '发送中...' : '发送' }}
        </el-button>
      </div>
    </div>

    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      <el-alert
        :title="error"
        type="error"
        show-icon
        :closable="true"
        @close="error = null"
      />
    </div>
  </div>
      </el-col>
      <el-col :span="8">
        <el-card>
          <el-row>
            <el-input v-model="state.apiKey" placeholder="请输入API Key"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="state.baseUrl" placeholder="请输入URL"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="state.modelUrl" placeholder="请输入Model URL"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="selectedModel" placeholder="请选择模型"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="state.temperature" placeholder="请输入temperature"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="state.top_k" placeholder="请输入top_k"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="state.top_p" placeholder="请输入top_p"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="state.presetText" type="textarea" :rows="5"  placeholder="请输入预设文本"></el-input>
          </el-row>
          <el-row>
            <el-input v-model="state.pattern" placeholder="请输入pattern"></el-input>
          </el-row>
          <el-row>
            <el-button type="primary" @click="autoPrompt">发送请求</el-button>
          </el-row>
          <el-row>
            <el-input v-model="exPromptStore.ai.tags" type="textarea" :rows="5"  placeholder="请输入预设文本"></el-input>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed, reactive, getCurrentInstance } from 'vue';
import OpenAI from 'openai';
import request from '@renderer/utils/request';
import { useExPrompt } from '@renderer/stores/useExPrompt';
import { useGenerationStore } from '@renderer/stores/useGenerationStore';


const instance = getCurrentInstance();
const cssVar = instance?.appContext.config.globalProperties.$cssVarName;
const exPromptStore = useExPrompt();
const generationStore = useGenerationStore()
const state = reactive({
    baseUrl: 'https://api.siliconflow.cn/v1',
    apiKey: 'sk-aerykdawqkqlrvqmmgdafrpqsiiscymknunnldlwheocvcfk',
    modelUrl: 'https://api.siliconflow.cn/v1/models',
    temperature: 1,
    top_k: 50,
    top_p: 0.7,
    presetText: "-返回50到60个符合Danbooru标签概念并采用特定格式(无下划线)的标签组合成字符串并必须使用```作为起止符号,添加适当的细节",
    pattern: ""
})

// 创建OpenAI客户端
const openai = new OpenAI({
  baseURL: state.baseUrl,
  apiKey: state.apiKey,
  dangerouslyAllowBrowser: true,
  defaultHeaders: {
    'HTTP-Referer': window.location.origin,
  },
});

// 响应式数据
const userInput = ref('');
const messages = ref([]);
const isLoading = ref(false);
const error = ref(null);
const availableModels = ref([]);
const selectedModel = ref('');
const isLoadingModels = ref(true);
const messagesContainer = ref(null);

// 计算属性 - 用于展示的模型提示
const modelTips = computed(() => {
  if (availableModels.value.length > 0) {
    return [
      availableModels.value[0],
      availableModels.value[Math.floor(availableModels.value.length / 2)],
      availableModels.value[availableModels.value.length - 1]
    ];
  }
  return [];
});

// 获取可用模型
const fetchAvailableModels = async () => {
  try {
    isLoadingModels.value = true;
    request({url:state.modelUrl,method:"get",params:{type:"text"},headers:{'Content-Type': 'application/json','Authorization': 'Bearer ' + state.apiKey}}).then((res)=>{
      if(res.status == 200 ){
          availableModels.value = res.data.data.map(model => ({
            name: model.id,
            slug: model.id,
            reasoning: model.id
          }));
      }
    })
  } catch (err) {
    console.error('获取模型列表失败:', err);
    error.value = '无法加载模型列表，请检查网络连接';
  } finally {
    isLoadingModels.value = false;
  }
};

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return;

  try {
    // 添加用户消息
    const userMessage = {
      role: 'user',
      content: userInput.value,
      timestamp: new Date()
    };

    messages.value.push(userMessage);

    const currentInput = userInput.value;
    userInput.value = '';
    isLoading.value = true;
    error.value = null;

    // 滚动到底部
    scrollToBottom();

    // 获取当前模型的信息
    const currentModel = availableModels.value.find(m => m.slug === selectedModel.value);
    const reasoningConfig = currentModel?.reasoning;

    // 准备API参数
    const params = {
      model: selectedModel.value,
      messages: [...messages.value.map(m => ({ role: m.role, content: m.content }))],
      temperature: state.temperature,
      top_k: state.top_k,
      top_p: state.top_p,
      stream: false,
    };

    // 如果模型支持推理标记，添加相关参数
    if (reasoningConfig) {
      params.reasoning = true;
      params.include_reasoning = true;
    }

    // 调用API
    const completion = await openai.chat.completions.create(params);


    // 添加AI回复
    const aiMessage = {
      ...completion.choices[0].message,
      timestamp: new Date()
    };

    messages.value.push(aiMessage);

    // 滚动到底部
    scrollToBottom();

  } catch (err) {
    console.error('API错误:', err);
    error.value = `错误: ${err.message || '获取响应失败'}`;

    // 添加错误消息到对话中
    messages.value.push({
      role: 'ai',
      content: `抱歉，处理您的请求时出错：${err.message || '未知错误'}`,
      timestamp: new Date(),
      isError: true
    });

    // 滚动到底部
    scrollToBottom();
  } finally {
    isLoading.value = false;
  }
};


const isAutoPromptRunning = ref(false);
const autoPromptInterval = ref(2000); // 默认间隔 2 秒
const maxIterations = ref(10); // 最大迭代次数
const currentIteration = ref(0); // 当前迭代次数

// 递归实现的自动提示
const autoPrompt = async () => {
  if (!isAutoPromptRunning.value) {
    // 如果是第一次启动，重置计数
    currentIteration.value = 0;
    isAutoPromptRunning.value = true;
  }

  // 检查是否达到最大迭代次数
  if (currentIteration.value >= maxIterations.value) {
    stopAutoPrompt();
    return;
  }

  try {
    // 1. 发送预设文本到API
    const completion = await openai.chat.completions.create({
      model: selectedModel.value,
      messages: [{ role: "user", content: state.presetText }],
      temperature: state.temperature,
      top_k: state.top_k,
      top_p: state.top_p,
      stream: false,
    });

    const aiResponse = completion.choices[0].message.content;

    // 2. 提取```包裹的提示词内容
    const regex = /```([\s\S]*?)```/;
    const match = aiResponse.match(regex);

    if (match && match[1]) {
      const promptText = match[1].trim();

      // 3. 将提示词内容写入
      exPromptStore.ai.tags = promptText;

      // 4. 调用生成图片函数
      await generationStore.generateImages();

      // 5. 添加消息到聊天界面
      messages.value.push({
        role: "user",
        content: state.presetText,
        timestamp: new Date()
      });

      messages.value.push({
        role: "ai",
        content: `已生成提示词并创建图片 (${currentIteration.value + 1}/${maxIterations.value}):\n\n${promptText}`,
        timestamp: new Date()
      });

      // 滚动到底部
      scrollToBottom();

      // 增加迭代计数
      currentIteration.value++;

      // 6. 递归调用自身（使用 setTimeout 避免栈溢出）
      if (isAutoPromptRunning.value) {
        setTimeout(autoPrompt, autoPromptInterval.value);
      }
    } else {
      setTimeout(autoPrompt, autoPromptInterval.value);
    }
  } catch (err) {
    console.error("自动提示出错:", err);
    error.value = `自动提示出错: ${err.message || "未知错误"}`;
    stopAutoPrompt();
  }
};

// 停止自动提示
const stopAutoPrompt = () => {
  isAutoPromptRunning.value = false;

  // 添加停止消息
  if (currentIteration.value > 0) {
    messages.value.push({
      role: "ai",
      content: `自动提示已停止，共完成 ${currentIteration.value} 次迭代`,
      timestamp: new Date()
    });
    scrollToBottom();
  }
};
// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 格式化消息内容（处理推理标记）
const formatMessage = (content) => {
  if (typeof content !== 'string') return content;

  // 如果有推理标记，添加样式
  return content
    .replace(/<think>/g, '<div class="thinking-tag">&lt;think&gt;</div><div class="thinking-content">')
    .replace(/<\/think>/g, '</div><div class="thinking-tag">&lt;/think&gt;</div>');
};

// 清空对话
const clearChat = () => {
  messages.value = [];
  error.value = null;
};

// 组件挂载时获取模型列表
onMounted(() => {
  fetchAvailableModels();

  // 加载本地存储的对话（可选）
  /*
  const savedChat = localStorage.getItem('ai_chat');
  if (savedChat) {
    try {
      messages.value = JSON.parse(savedChat);
    } catch (e) {
      console.error('加载对话失败', e);
    }
  }*/
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  background-color: var(--el-bg-color-page);
  border-radius: 16px;
  box-shadow: var(--el-box-shadow-light);
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.control-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.model-selector {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.model-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.model-name {
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--el-text-color-regular);
}

.model-badge {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}

.loading-button {
  width: 160px;
}

.action-buttons {
  margin-left: 10px;
}

.messages-container {
  flex: 1;
  overflow: hidden;
  border-radius: 12px;
  background-color: var(--el-bg-color);
  box-shadow: var(--el-box-shadow-light);
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.message {
  display: flex;
  gap: 16px;
  animation: fadeIn 0.3s ease-out;
}

.message.user {
  flex-direction: row-reverse;
}

.message-header {
  display: flex;
  align-items: baseline;
  margin-bottom: 6px;
}

.message-header strong {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.message-header .timestamp {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  margin-left: 10px;
}

.message-body {
  font-size: 15px;
  line-height: 1.6;
  padding: 14px 18px;
  border-radius: 12px;
  box-shadow: var(--el-box-shadow-light);
}

.message.user .message-body {
  background-color: var(--el-color-primary-light-9);
  border-bottom-right-radius: 2px;
  color: var(--el-color-primary);
}

.message.ai .message-body {
  background-color: var(--el-color-success-light-9);
  border-bottom-left-radius: 2px;
  color: var(--el-text-color-primary);
}

.thinking .message-body {
  background-color: var(--el-fill-color-lighter);
}

.avatar {
  flex-shrink: 0;
}

.user-avatar {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.ai-avatar {
  background-color: var(--el-color-success-light-9);
  color: var(--el-color-success);
}

.input-area {
  background-color: var(--el-bg-color);
  border-radius: 12px;
  padding: 16px;
  box-shadow: var(--el-box-shadow-light);
}

.input-textarea :deep(.el-textarea__inner) {
  border: none;
  box-shadow: none !important;
  font-size: 15px;
  padding: 12px 16px;
  resize: none;
  max-height: 150px;
  background-color: var(--el-fill-color-lighter);
  color: var(--el-text-color-regular);
}

.input-textarea :deep(.el-textarea__inner:focus) {
  box-shadow: none !important;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.action-button {
  background-color: var(--el-fill-color);
  border: none;
  color: var(--el-text-color-secondary);
}

.send-button {
  padding: 10px 28px;
  font-weight: 500;
  background-color: var(--el-color-primary);
  color: var(--el-color-white);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--el-text-color-placeholder);
  text-align: center;
  padding: 40px 20px;
}

.empty-content {
  max-width: 400px;
}

.empty-icon {
  color: var(--el-border-color);
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 20px;
  margin-bottom: 10px;
  color: var(--el-text-color-primary);
}

.empty-state p {
  margin-bottom: 24px;
  color: var(--el-text-color-regular);
}

.model-tips {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.error-message {
  margin-top: 15px;
  color: var(--el-color-danger);
}

.thinking-indicator {
  display: flex;
  align-items: center;
  color: var(--el-text-color-secondary);
}

.thinking-indicator .dot {
  animation: blink 1.5s infinite;
  opacity: 0;
  background-color: var(--el-text-color-secondary);
}

.thinking-indicator .dot:nth-child(1) {
  animation-delay: 0.2s;
}
.thinking-indicator .dot:nth-child(2) {
  animation-delay: 0.4s;
}
.thinking-indicator .dot:nth-child(3) {
  animation-delay: 0.6s;
}

/* 思考内容样式 */
.thinking-tag {
  font-family: monospace;
  color: var(--el-text-color-secondary);
  font-size: 0.9em;
  margin: 5px 0;
}

.thinking-content {
  background-color: var(--el-color-warning-light-9);
  border-left: 3px solid var(--el-color-warning);
  padding: 8px 12px;
  margin: 5px 0;
  border-radius: 0 4px 4px 0;
  font-family: monospace;
  white-space: pre-wrap;
  color: var(--el-text-color-primary);
}

@keyframes blink {
  0%, 100% { opacity: 0; }
  50% { opacity: 1; }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
  .chat-container {
    padding: 12px;
    height: auto;
  }

  .control-area {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .action-buttons {
    margin-left: 0;
    display: flex;
    justify-content: flex-end;
  }

  .message {
    gap: 12px;
  }

  .message-body {
    padding: 10px 14px;
    font-size: 14px;
  }
}
</style>
